//    Copyright (C) Kherty.  All rights reserved.
using System.Diagnostics.Contracts;
using OpenLS.Core.Serialization;
using OpenLS.Spreadsheet.Office2003;
using OpenLS.Spreadsheet.Parsing;

namespace OpenLS.Spreadsheet
{
    partial class Workbook : IOffice2003XmlSerializable
	{
        #region IXmlSpreadsheetSerializable Members

        void IOffice2003XmlSerializable.ReadXmlSpreadsheet(ReadContext context)
        {
            WorkbookResolver resolver = new WorkbookResolver(this, true);
            context.AddData<WorkbookResolver>(resolver);
            _namingConvention = CellNamingConventions.R1C1NamingConvention;
            Sheets.Clear();
            StyleLookup styleLookup = context.GetData<StyleLookup>();
            using (ReadContext c = context.Read("Workbook"))
            {
                c.EatForNow("DocumentProperties");
                c.EatForNow("CustomDocumentProperties");
                c.EatForNow("OfficeDocumentSettings");
                c.EatForNow("ExcelWorkbook");
                if (c.ReaderLocalName == "Styles")
                {
                    using (ReadContext stylesC = c.Read("Styles"))
                    {
                        while (stylesC.ReaderLocalName == "Style")
                        {
                            CellFormattingRecord r = new CellFormattingRecord();
                            IOffice2003XmlSerializable s = r;
                            s.ReadXmlSpreadsheet(stylesC);
                            var old = StyleSheet.AddStyleRecord(r);
                            if (old != null)
                            {
                                styleLookup.Remove(styleLookup.LastKey);
                                styleLookup.Add(styleLookup.LastKey, (CellFormattingRecord) old);
                            }
                        }
                    }
                }
                c.EatForNow("Names");
                while (c.ReaderLocalName == "Worksheet")
                {
                    Worksheet ws = new Worksheet(this, "");
                    Sheets.Add(ws);
                    IOffice2003XmlSerializable s = ws;
                    s.ReadXmlSpreadsheet(c);
                }
                while (c.ReaderLocalName == "PivotCache")
                    c.EatForNow("PivotCache");
            }
            resolver.ResolveAll();
            _namingConvention = CellNamingConventions.A1NamingConvention;

        }

        #endregion
    }
}
